package com.adnaan.backend.common.mail.service;

import com.adnaan.backend.common.mail.config.EMailProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {

    private final JavaMailSender mailSender;
    private final EMailProperties eMailProperties;
    private final Configuration configuration;

    /**
     * 发送简单文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendSimpleMail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(eMailProperties.getUsername());
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("发送简单邮件成功：{}", to);
        } catch (Exception e) {
            log.error("发送简单邮件失败：{}", e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content HTML内容
     */
    @Async
    public CompletableFuture<Void> sendHtmlMailAsync(String to, String subject, String content) {
        return CompletableFuture.runAsync(() -> {
            try {
                sendHtmlMail(to, subject, content);
            } catch (Exception e) {
                log.error("异步发送HTML邮件失败：{}", e.getMessage());
                throw new RuntimeException("异步邮件发送失败", e);
            }
        });
    }

    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(eMailProperties.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            log.info("发送HTML邮件成功：{}", to);
        } catch (Exception e) {
            log.error("发送HTML邮件失败：{}", e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件路径
     */
    @Async
    public CompletableFuture<Void> sendAttachmentsMailAsync(String to, String subject, String content, String filePath) {
        return CompletableFuture.runAsync(() -> {
            try {
                sendAttachmentsMail(to, subject, content, filePath);
            } catch (Exception e) {
                log.error("异步发送带附件邮件失败：{}", e.getMessage());
                throw new RuntimeException("异步邮件发送失败", e);
            }
        });
    }

    public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(eMailProperties.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            log.info("发送带附件邮件成功：{}, 附件：{}", to, filePath);
        } catch (Exception e) {
            log.error("发送带附件邮件失败：{}", e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 发送带附件的邮件（MultipartFile类型）
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     * @param file    附件
     */
    @Async
    public CompletableFuture<Void> sendAttachmentsMailAsync(String to, String subject, String content, MultipartFile file) {
        return CompletableFuture.runAsync(() -> {
            try {
                sendAttachmentsMail(to, subject, content, file);
            } catch (Exception e) {
                log.error("异步发送带附件邮件失败：{}", e.getMessage());
                throw new RuntimeException("异步邮件发送失败", e);
            }
        });
    }

    public void sendAttachmentsMail(String to, String subject, String content, MultipartFile file) throws MessagingException, IOException {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(eMailProperties.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.addAttachment(file.getOriginalFilename(), file);
            mailSender.send(message);
            log.info("发送带附件邮件成功：{}, 附件：{}", to, file.getOriginalFilename());
        } catch (Exception e) {
            log.error("发送带附件邮件失败：{}", e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 发送基于模板的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param template 模板名称
     * @param model    模板参数
     */
    @Async
    public CompletableFuture<Void> sendTemplateMailAsync(String to, String subject, String template, Map<String, Object> model) {
        return CompletableFuture.runAsync(() -> {
            try {
                sendTemplateMail(to, subject, template, model);
            } catch (Exception e) {
                log.error("异步发送模板邮件失败：{}", e.getMessage());
                throw new RuntimeException("异步邮件发送失败", e);
            }
        });
    }

    public void sendTemplateMail(String to, String subject, String template, Map<String, Object> model) throws Exception {
        try {
            Template templateObj = configuration.getTemplate(template);
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(templateObj, model);
            sendHtmlMail(to, subject, content);
            log.info("发送模板邮件成功：{}, 模板：{}", to, template);
        } catch (Exception e) {
            log.error("发送模板邮件失败：{}", e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 批量发送简单邮件
     *
     * @param toList  收件人列表
     * @param subject 主题
     * @param content 内容
     */
    @Async
    public CompletableFuture<Void> sendSimpleMailBatch(List<String> toList, String subject, String content) {
        return CompletableFuture.runAsync(() -> {
            for (String to : toList) {
                try {
                    sendSimpleMail(to, subject, content);
                } catch (Exception e) {
                    log.error("批量发送邮件失败，收件人：{}, 错误：{}", to, e.getMessage());
                }
            }
        });
    }

    /**
     * 批量发送HTML邮件
     *
     * @param toList  收件人列表
     * @param subject 主题
     * @param content HTML内容
     */
    @Async
    public CompletableFuture<Void> sendHtmlMailBatch(List<String> toList, String subject, String content) {
        return CompletableFuture.runAsync(() -> {
            for (String to : toList) {
                try {
                    sendHtmlMail(to, subject, content);
                } catch (Exception e) {
                    log.error("批量发送HTML邮件失败，收件人：{}, 错误：{}", to, e.getMessage());
                }
            }
        });
    }
}